package constant.milk.cashbook.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import constant.milk.cashbook.R;
import constant.milk.cashbook.SuperActivity;
import constant.milk.cashbook.bean.MintFileData;
import constant.milk.cashbook.database.DbAdapter;
import constant.milk.cashbook.tip.TipInfoActivity;
import constant.milk.cashbook.tip.TipMap;
import constant.milk.cashbook.util.MilkTextView;
import constant.milk.cashbook.util.MilkUtil;

public class DataRollBankActivity extends SuperActivity
{
	private ListView listView;
	
	private Button deleteButton;
	private Button rollBankButton;
	
	private RollBankListAdapter listAdapter;
	
	private String items;
	
	private File [] readFiles;
	
	private File [] readAutoFiles;
	
	private MintFileData selectData;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.data_rollbank_activity);
		
		setTitle("데이터복구");
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		listView = (ListView) findViewById(R.id.listView);
		
		deleteButton = (Button) findViewById(R.id.deleteButton);
		rollBankButton = (Button) findViewById(R.id.rollBankButton);
	}

	@Override
	protected void setOnClick()
	{
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (items.equals("") || selectData == null)
				{
					MilkUtil.showToast(superContext, "선택된 파일이 없습니다.");
					return;
				}
				
				if (setDelete())
				{
					MilkUtil.showDialogFinish(superContext, "확인", "데이터 삭제에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
		
		rollBankButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (items.equals("") || selectData == null)
				{
					MilkUtil.showToast(superContext, "선택된 파일이 없습니다.");
					return;
				}
				
				if (setRollBankData())
				{
					MilkUtil.showDialogFinish(superContext, "확인", "데이터 복구에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		ArrayList<MintFileData> list = new ArrayList<MintFileData>();
		
		try
		{
			File directory = new File(Environment.getExternalStorageDirectory() + "/" 
										+ DataMainActivity.dirName);
			
			readFiles = directory.listFiles(new FilenameFilter()
			{
				@Override
				public boolean accept(File dir, String filename)
				{
					return filename.endsWith(".db");
				}
			});
			
			File directory2 = new File(Environment.getExternalStorageDirectory() + "/" 
										+ DataMainActivity.dirNameAuto);
			
			readAutoFiles = directory2.listFiles(new FilenameFilter()
			{
				@Override
				public boolean accept(File dir, String filename)
				{
					return filename.endsWith(".db");
				}
			});
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		
		if (readFiles != null)
		{
			for (int i = readFiles.length - 1; i > -1 ; i--)
			{
				MintFileData data = new MintFileData();
				data.setFileName(readFiles[i].getName());
				data.setData(readFiles[i]);
				data.setAutoYN("1");
				list.add(data);
			}
		}
		
		if (readAutoFiles != null)
		{
			for (int i = readAutoFiles.length - 1; i > -1 ; i--)
			{
				MintFileData data = new MintFileData();
				data.setFileName(readAutoFiles[i].getName());
				data.setData(readAutoFiles[i]);
				data.setAutoYN("0");
				list.add(data);
			}
		}
		
		listView.setOnItemClickListener(onItemClickListener);
		
		listAdapter = new RollBankListAdapter(
				superContext, R.layout.radio_list_item, list);
		listView.setAdapter(listAdapter);
		
		if (list.size() > 0)
		{
			selectData = list.get(0);
			items = selectData.getFileName();
		}
		else
		{
			selectData = null;
			items = "";
		}
	}
	
	private boolean setRollBankData()
	{
		DbAdapter adapter = DbAdapter.getInstance();
		String path = adapter.getDbPath(superContext);
		adapter.close();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		
		try
		{
			String filePath = selectData.getData().getPath();
			SQLiteDatabase db = SQLiteDatabase.openDatabase(filePath, 
					null, SQLiteDatabase.CREATE_IF_NECESSARY);
			
			if (!db.isOpen())
			{
				return false;
			}
			
			db.close();
			
			fis = new FileInputStream(selectData.getData());
			
			File writeFile = new File(path);
			
			fos = new FileOutputStream(writeFile);
			
			byte [] buffer = new byte[1024];
			
			int bufBytes = 0;
			while ((bufBytes = fis.read(buffer)) != -1) 
			{
				fos.write(buffer, 0, bufBytes);
			}
			fos.flush();
			
		} catch (Exception e)
		{
			return false;
		} finally {
			try
			{
				if (fis != null) fis.close();
				if (fos != null) fos.close();
			} catch (IOException e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setDelete()
	{
		String filePath = "";
		
		if (selectData.getAutoYN().equals("1"))
		{
			filePath = "/" + DataMainActivity.dirName + "/";
		}
		else
		{
			filePath = "/" + DataMainActivity.dirNameAuto + "/";
		}
		
		File file = new File(Environment.getExternalStorageDirectory() + filePath + selectData.getFileName());
		
		return file.delete();
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			selectData = (MintFileData) arg0.getItemAtPosition(position);
			items = selectData.getFileName();
			listAdapter.notifyDataSetChanged();
		}
	};
	
	/**
	 * 리스트 아답터
	 */
	private class RollBankListAdapter extends ArrayAdapter<MintFileData> 
	{
		public RollBankListAdapter(Context context, int textViewResourceId, ArrayList<MintFileData> list) 
		{
			super(context, textViewResourceId, list);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			View v = convertView;
			
			if (v == null) 
			{
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.radio_list_item, null);
			}
			
			MintFileData data = getItem(position);
			
			MilkTextView nameTextView = (MilkTextView) v.findViewById(R.id.radioItemNameTextView);
			RadioButton radioButton = (RadioButton) v.findViewById(R.id.radioItemRadio);
			
			nameTextView.setTextSize(TEXT_SIZE);
			nameTextView.setText(data.getFileName());
			
			if (items.equals(data.getFileName()))
			{
				radioButton.setChecked(true);
			}
			else
			{
				radioButton.setChecked(false);
			}
			
			return v;
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(superContext, TipInfoActivity.class);
		intent.putExtra(TipInfoActivity.TIP_ID, TipMap.TIP_DATA_ROLLBACK);
		startActivity(intent);
	}

}
